package com.zms.parallel;

import java.lang.management.ManagementFactory;

public class ParallelComputing {

    public static int NCPUS;
    static {
        NCPUS= ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
    }

    public static void runMultiTask(int len,MyTask task) throws Exception {
        runMultiTask(len,task,false);
    }
    public static void runMultiTask(int len,MyTask task,boolean debug) throws Exception {
        runMultiTask(len,task,NCPUS,debug);
    }
    public static void runMultiTask(int len,MyTask task,int cpus) throws Exception {
        runMultiTask(len,task,cpus,false);
    }

    public static void runMultiTask(int len,MyTask task,int cpus,boolean debug) throws Exception {
        if(cpus<2) {
            /*for(int i=0;i<len;i++) {
                task.run(i);
            }*/
            MyTaskRunner test=new MyTaskRunner(task,debug);
            test.from=0;
            test.to = len;
            test.run();
        } else {
            boolean[] flags=new boolean[cpus];
            int num=0;
            int step=len/cpus;
            for(int i=0;i<cpus;i++) {
                MyTaskRunner test=new MyTaskRunner(task,debug);
                test.from = num;
                if(i==0) {
                    num+=(step+(len-step*cpus));
                } else {
                    num+=step;
                }
                test.to=num;
                test.flags=flags;
                test.index=i;
                Thread thread=new Thread(test);
                thread.setDaemon(true);
                thread.start();
            }
            boolean ok=false;
            while(!ok) {
                ok=true;
                for(int i=0;i<cpus;i++) {
                    if(!flags[i]) {
                        ok=false;
                        break;
                    }
                }
                Thread.sleep(50);
            }
        }
    }
}
